"""
@Project:study_platform
@File:pay.py
@Author:韩晓雷
@Date:19:54
"""
import redis
from alipay import AliPay
from django.conf import settings

# 读取app私钥
app_private_key_string = open(settings.APP_PRIVATE_KEY_PATH, 'r').read()
# 读取支付宝公钥
alipay_public_key_string = open(settings.ALIPAY_PUBLIC_KEY_PATH, 'r').read()


def redis_conn():
    r = redis.Redis(host='localhost',port=6379,db=0)
    return r


# 支付
class MyAlipay:

    def __init__(self, *args, **kwargs):
        super().__init__(*args, **kwargs)

        self.alipay = AliPay(
            appid="2021000119635066",
            app_private_key_string=app_private_key_string,
            alipay_public_key_string=alipay_public_key_string,
            app_notify_url=None,
            sign_type='RSA2',
            debug=True,
        )

    def get_pay_url(self, order_id, total_amount, return_url):
        order_string = self.alipay.api_alipay_trade_page_pay(
            subject="商家收款",
            out_trade_no=order_id,
            total_amount=total_amount,
            return_url=return_url,
            notify_url=return_url,
        )
        # 支付地址
        return "https://openapi.alipaydev.com/gateway.do?" + order_string

    def check(self, out_trade_no):
        try:
            # 主动查询支付结果
            pay_result = self.alipay.api_alipay_trade_query(out_trade_no)
            # 获取支付状态
            trade_staus = pay_result.get("trade_status")
            if trade_staus == "TRADE_SUCCESS":
                # 支付成功
                return True
                # 删除购物车已购买的商品
            else:
                # 支付失败
                return False
        except Exception as e:
            print("校验支付异常", e)
            return False


#  买家账号： fflpkl0295@sandbox.com
#  登陆密码： 111111
#  支付密码： 111111


